import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


//定义Message类来描述这个请求里的body,方便Jackson进行json解析
class Message{
    public String from;
    public String to;
    public String message;
}
@WebServlet("/messageWall/Message")
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    //private List<Message> messageList = new ArrayList<>();
    // 向服务器提交数据
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //ObjectMapper objectMapper = new ObjectMapper();
        //把body里面的内容通过流对象读取出来，解析成一个Message对象
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        //解析出后的Message对象需要被保存,此处通过一个List来进行保存
        //messageList.add(message);
        save(message);
        //此处的状态码可以省略，不设置默认就是200
        resp.setStatus(200);
    }
    // 从服务器获取数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //ObjectMapper objectMapper = new ObjectMapper();
        //显式地告诉浏览器，数据是json格式的字符串，字符集为utf8
        resp.setContentType("application/json;charset=utf8");
        //writeValue将Java对象转换成json格式的字符串，getWrite将转换成的json格式字符串写入到响应body中
        //objectMapper.writeValue(resp.getWriter(),messageList);

        //使用writeValueAsString()方法将messageList转换成json格式的字符串，再存储到jsonResp变量中
        List<Message> messageList = load();
        String jsonResp = objectMapper.writeValueAsString(messageList);
        System.out.println("jsonResp = " + jsonResp);
        //getWrite()构成一个write对象，该对象再调用write()方法将转换成的json格式字符串写入到响应body中
        resp.getWriter().write(jsonResp);
    }

    //从服务器删除数据
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        delete();
        List<Message> messageList = load();
        String jsonResp = objectMapper.writeValueAsString(messageList);
        System.out.println("jsonResp = " + jsonResp);
        resp.getWriter().write(jsonResp);
    }

    //往数据库存取一条数据记录
    private void save(Message message){
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "insert into message(`from`,`to`,message) value(?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, message.from);
            statement.setString(2, message.to);
            statement.setString(3,message.message);
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.save(connection,statement);
        }
    }

    //从数据库中获取数据记录
    private List<Message> load(){
        List<Message> messageList = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from message";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while(resultSet.next()){
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messageList.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.save(connection,statement,resultSet);
        }
        return messageList;
    }

    //删除数据库中的一条记录
    private void delete(){
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "delete from message where id = (select * from(select max(id) from message) as temp);";
            statement = connection.prepareStatement(sql);
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.save(connection,statement);
        }
    }
}


